import React, { Component, createRef } from 'react';
//  引入验证码组件
import Captcha from '../../components/Captcha';
// 引入对应的组件antd
import { Form, Input, Button, Space, message } from 'antd';
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons';
// 引入withRouter
import { withRouter } from 'react-router-dom'
// 导入url.js 接口地址
import url from '@/config/url'
// 导入封装好的axios请求
import req from '@/http/request.js'
class Mobilelogin extends Component {
    state = {
        key: '', // 图形验证码对应的key
        requestId: '', // 手机短信验证码对应的id
        time: 5, // 倒计时初始时间
        disableClick: false, // 按钮是否可以点击
    }
    ref1 = createRef()  // 创建ref对象 
    ref2 = createRef()  // 创建表单实例对象
    timer = null // 定时器
    render() {
        return (
            <Form
                name="normal_login"
                className="login-form"
                initialValues={{ remember: true }}
                onFinish={this.onFinish}
                ref={this.ref2}
            >
                <Form.Item
                    name="mobile"
                    rules={[{
                        required: true,// 正则表达式一定不要加引号
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入手机号!'
                    }]}
                >
                    <Input size='large' prefix={<UserOutlined className="site-form-item-icon" />} placeholder="手机号" />
                </Form.Item>
                <Form.Item
                    name="captcha"
                    rules={[{ required: true, message: '请输入图形验证码!' }]}
                >
                    <Space>
                        <Input
                            size='large'
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="text"
                            placeholder="图形验证码"
                        />
                        {/*验证码*/}
                        <Captcha saveKey={this.getData} ref={this.ref1} w='140px' h='40px'></Captcha>
                    </Space>
                </Form.Item>
                <Form.Item
                    name="code"
                    rules={[{ required: true, message: '请输入短信验证码!' }]}
                >
                    <Space>
                        <Input
                            size='large'
                            prefix={<KeyOutlined className="site-form-item-icon" />}
                            type="text"
                            placeholder="短信验证码"
                        />
                        <Button onClick={this.sendCode} disabled={this.state.disableClick}>{this.state.time === 5 ? '发送验证码' : this.state.time + '秒后获取'}</Button>
                    </Space>
                </Form.Item>
                <Form.Item>
                    <Button size='large' type="primary" block htmlType="submit" className="login-form-button">
                        登录
                    </Button>
                </Form.Item>
            </Form>
        );
    }

    // 定义一个方法,参数接受来自子组件的数据
    getData = (key) => {
        this.setState({
            key: key
        })
    }
    // 点击发送验证码
    sendCode = () => {
        //console.log('发送');
        // 01: 点击发送手机验证码时候,先验证手机号是否填写正确,图形验证码是否正确
        this.ref2.current.validateFields(['mobile', 'captcha']).then(res => {
            // 此处表示验证mobile 和 captcha 成功
            //console.log(res); // {mobile: '15510052553', captcha: '1'}
            // 02: 验证图形验证码是否正确
            req.post(url.verifyCap, {
                key: this.state.key,
                captcha: res.captcha
            }).then(res1 => {
                if (res1.data.errNo === 0) {
                    // 此刻表示图形验证码验证成功
                    req.post(url.sendCode, {
                        token: res1.data.context.token,
                        mobile: res.mobile,
                        type: 0,
                    }).then(res2 => {
                        // 此处表示手机验证码发送成功
                        if (res2.data.errNo === 0) {
                            this.setState({
                                requestId: res2.data.requestId
                            })
                            message.success("短信下发成功！")
                            // 开始计时
                            this.timeDown()
                            this.setState({
                                disableClick: true
                            })
                        } else {
                            // 此处表示手机验证码发送失败
                            message.error(res2.data.errText)
                            this.ref1.current.loadCaptcha()
                        }

                    }).catch(e => {

                    })
                } else {
                    // 图形验证码失败
                    message.error(res1.data.errText)
                    // 刷新验证码
                    this.ref1.current.loadCaptcha()
                }
            })

        }).catch(e => {
            // 此处表示验证 mobile 和 captcha 失败
            console.log(e);
        })
    }

    // 倒计时函数
    timeDown = () => {
        if (this.state.time === 0) {
            this.setState({
                time: 5,
                disableClick: false
            })

        } else {
            // 处于倒计时阶段（-1阶段）
            this.setState({
                time: this.state.time - 1
            })
            // 重复执行
            this.timer = setTimeout(() => {
                this.timeDown()
            }, 1000)
        }
    }
    // 点击提交
    onFinish = (values) => {
        //console.log(values)
        req.post(url.mobilelogin, {
            code: values.code,
            requestId: this.state.requestId,
            mobile: values.mobile
        }).then(res => {
            if (res.data.errNo === 0) {
                // 登录成功（提示+跳转到后台首页）
                message.success("登录成功！", 2, () => this.props.history.push("/dashboard"))
            } else {
                // 登录失败（提示+刷新验证码）
                message.error(res.data.errText)
                this.ref1.current.loadCaptcha()
            }
        })
    };
    componentWillUnmount() {
        clearTimeout(this.timer)
    }
}

export default withRouter(Mobilelogin);
